#!/bin/bash -x
. $TONE_ROOT/lib/disk.sh

FIO_GIT_URL="https://gitee.com/anolis/fio.git"
XFSTESTS_GIT_URL="https://gitee.com/anolis/xfstests.git"
DEP_PKG_LIST="acl attr gawk bc  dump e2fsprogs gawk gcc 
        libtool lvm2 make psmisc quota sed xfsdump  libacl-devel libattr-devel dbench indent
        libaio-devel libuuid-devel python36 sqlite libblkid-devel fio xfsprogs xfsprogs-devel patch"
FIO_BRANCH="anolis"
TONE_CAN_SKIP_PKG=yes

kernel_ver=$(uname -r | awk -F '.' '{print$1"."$2}')
os_ver=$(uname -r | awk -F '.' '{print$(NF-1)}')


if [ -n "$BRANCH" ]; then
    branch="$BRANCH"
else
    kver=$(uname -r | cut -d. -f1)
    if [[ $kver -le 4 ]]; then
        branch="anck-4.19"
    elif [[ $kver -eq 5 ]]; then
        branch="anck-5.10"
    elif [[ $kver -eq 6 ]]; then
        branch="anck-6.6"
    else
        branch="master"
    fi
fi

fetch()
{
    echo "\$XFSTESTS_GIT_URL for git clone or update"
    git_clone_mirror $XFSTESTS_GIT_URL $TONE_BM_CACHE_DIR/xfstests-dev
    echo "\$FIO_GIT_URL  for git clone or update"
    git_clone_mirror $FIO_GIT_URL $TONE_BM_CACHE_DIR/fio
}

extract_src()
{
    set_git_clone

    echo "Clone xfstests code to build path"
    mkdir $TONE_BM_BUILD_DIR/xfstests-dev
    cd "$TONE_BM_BUILD_DIR/xfstests-dev" || exit 1
    git_clone_exec "$TONE_BM_CACHE_DIR/xfstests-dev" "$TONE_BM_BUILD_DIR/xfstests-dev" --branch "$branch"

    # build fio from source code and overwrite system version
    fio_ver=$(fio --version 2>/dev/null | sed 's/fio-//g' | cut -d. -f1)
    if [ -z "$fio_ver" ] || [ "$fio_ver" -lt 3 ]; then
        echo "Clone fio code to build path"
        mkdir $TONE_BM_BUILD_DIR/fio
        cd "$TONE_BM_BUILD_DIR/fio" || exit 1
        git_clone_exec "$TONE_BM_CACHE_DIR/fio" "$TONE_BM_BUILD_DIR/fio" --branch "$FIO_BRANCH"
    fi
}

build_xfstests(){
    cd $TONE_BM_BUILD_DIR/xfstests-dev
    if [ x"$os_ver" == x"an7" -a x"$kernel_ver" == x"4.19" ]; then
        patch_dir=$TONE_BM_SUITE_DIR/patch/4.19/an7/
        [ -f $patch_dir/compile_err.patch ] && patch -p1 < $patch_dir/compile_err.patch
    fi
    make configure || return
    ./configure --prefix=$TONE_RUN_DIR/
    make && make install
}

fio_build_install()
{
    [ -d "$TONE_BM_BUILD_DIR/fio" ] || return
    # remove system version fio
    rpm -qa | grep -q fio && rpm -e fio
    # build fio from source code
    cd $TONE_BM_BUILD_DIR/fio
    ./configure
    make
    make install
}

build()
{
    export CFLAGS="-fcommon"
    fio_build_install
    build_xfstests || return
}

install()
{
    :
}
